package compare;

import java.util.Arrays;

/*
* java比较器
* */
public class CompareTest {
    public static void main(String[] args) {

        /*
        * Comparable接口
        * 1、实现Comparable
        * 2、重写compareTo（obj）方法
        * 3、重写规则，
        *   如果当前对象this大于形参obj，返回正整数
        *   如果当前对象this小于形参obj，返回负整数
        *   如果当前对象this等于形参obj，返回零
        * */

        Goods [] goods = new Goods[5];
        goods[0] = new Goods("a",42.1);
        goods[1] = new Goods("b",22.1);
        goods[2] = new Goods("c",52.1);
        goods[3] = new Goods("d",22.1);
        goods[4] = new Goods("e",82.1);

        Arrays.sort(goods);
        System.out.println(Arrays.toString(goods));
    }
}
class Goods implements Comparable{
    private String name;
    private double price;

    public Goods() {
    }

    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }




    //希望按照价格从低到高排序,若价格相等按名字排序
    @Override
    public int compareTo(Object o) {
        if (o instanceof Goods){
            Goods goods = (Goods)o ;
            //方式一：自己写
            if(this.price>goods.price){
                return 1;
            }else if(this.price<goods.price){
                return -1;
            }else {
                return this.name.compareTo(goods.name);
            }
            //方式二：调用方法
            //return Double.compare(this.price,goods.price);
        }
        throw new RuntimeException("传入的数据类型不一致");
    }
}
